package com.zjsru.plan2024.codeBase.fifty;

import java.util.HashMap;
import java.util.Map;

/**
 * 389. 找不同
 * @Author: cookLee
 * @Date: 2024-06-10
 */
public class FindTheDifference {

    /**
     * 主
     * \
     * 输入：s = "abcd", t = "abcde"
     * 输出："e"
     * 解释：'e' 是那个被添加的字母。
     * \
     * 输入：s = "", t = "y"
     * 输出："y"
     * \
     * @param args args
     */
    public static void main(String[] args) {
        FindTheDifference findTheDifference = new FindTheDifference();
        String s = "abcd";
        String t = "abcde";
        System.out.println(findTheDifference.findTheDifference2(s, t));
    }

    /**
     * 哈希表
     *
     * @param s s
     * @param t t
     * @return char
     */
    public char findTheDifference(String s, String t) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
        }
        for (int i = 0; i < t.length(); i++) {
            map.put(t.charAt(i), map.getOrDefault(t.charAt(i), 0) + 1);
        }
        Character key = map.entrySet().stream().filter(v -> v.getValue() % 2 == 1).findFirst().get().getKey();
        return key;
    }

    /**
     * 位运算
     *
     * @param s s
     * @param t t
     * @return char
     */
    public char findTheDifference2(String s, String t) {
        char result = 0;
        for (char c : s.toCharArray()) {
            result ^= c;
        }
        for (char c : t.toCharArray()) {
            result ^= c;
        }
        return result;
    }

    /**
     * 计数
     *
     * @param s s
     * @param t t
     * @return char
     */
    public char findTheDifference3(String s, String t) {
        int[] cnt = new int[26];
        for (int i = 0; i < s.length(); ++i) {
            char ch = s.charAt(i);
            cnt[ch - 'a']++;
        }
        for (int i = 0; i < t.length(); ++i) {
            char ch = t.charAt(i);
            cnt[ch - 'a']--;
            if (cnt[ch - 'a'] < 0) {
                return ch;
            }
        }
        return ' ';
    }

}
